package com.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.constant.YsConstant;
import com.common.vo.dd.DingDingTextVo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class DingDingUtils {

    private static OkHttpClient client = new OkHttpClient();


    //宋
    private static final String ddUrl = "https://oapi.dingtalk.com/robot/send?access_token=f853913ec8c2c6922fac8b8f3b80ae7743ecbba92d95162ff8000cbc9d775ccb";

    //王 hello
    private static final String dUrl = "https://oapi.dingtalk.com/robot/send?access_token=7b6f4b9c87c3b95e95a2aedf777851f06402c8008e74e82e096dbfeedccedc65";


    /**
     * 发送钉钉消息
     *
     * @param data 消息内容
     * @return
     */
    public static boolean sendToDingDing(String data,String type) {

        DingDingTextVo dingTextVo = DingDingTextVo.builder()
                .content(data).msgType(type)
                .build();
        return sendMesDingDing(dingTextVo.getJSONObjectString());
    }

    /**
     * 发送告警信息纯文本到钉钉@手机号
     *
     * @param content
     * @return
     */
    public static boolean sendTextToDD(String content) {
        DingDingTextVo dingTextVo = DingDingTextVo.builder()
                .content(content).isAtAll(true).msgType("text")
                .atMobiles(Arrays.asList(YsConstant.DEFAULT_PHONE))
                .build();
        return sendMesDingDing(dingTextVo.getJSONObjectString());
    }

    /**
     * 发送消息到钉钉公用方法
     *
     * @param dataUrl
     * @return
     */
    private static Boolean sendMesDingDing(String dataUrl) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(dataUrl);
            String content = JSONObject.parseObject(jsonObject.getString("text")).getString("content");
            String type = "application/json; charset=utf-8";
            RequestBody body = RequestBody.create(MediaType.parse(type), content);
            Request.Builder builder = new Request.Builder().url(ddUrl);
            builder.addHeader("Content-Type", type).post(body);

            Request request = builder.build();
            Response response = client.newCall(request).execute();
            String str = response.body().string();
            log.info("response.body()" + str);
            log.info("send dingDing message:" + FastJsonUtils.toJSONString(response.body()));
            JSONObject res = JSONObject.parseObject(str);
            return res.getIntValue("errcode") == 0;

        } catch (Exception e) {
            log.error("发送钉钉消息异常！");
            e.printStackTrace();
            return false;
        }
    }

}
